/*
 * Copyright 2014 Walter Lütgenau.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package offset.nodes.client.dialog.menu.view;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import offset.nodes.client.dialog.navigation.model.JSWindow;

/**
 *
 * @author Walter Lütgenau
 */
public class JSFAction extends AbstractAction {

    /**
     * Run the applet dialog
     */
    class JSFRunner implements Runnable {
        public static final String DELIMITER_JSF_ID = ":";
        public static final String WINDOW_ID_TOP = "_top";

        JSWindow window;
        String form;
        String jsfId;
        String windowId;

        /**
         * Call javascript to run the applet.
         *
         * @param document the document used to call javascript
         * @param appletId the id of the applet
         */
        public JSFRunner(JSWindow window, String jsfId) {
            this.window = window;
            String[] jsfParameters = jsfId.split(DELIMITER_JSF_ID);
            this.form = jsfParameters[0];
            if (jsfParameters[jsfParameters.length - 1].equals(WINDOW_ID_TOP)) {
                windowId = jsfParameters[jsfParameters.length - 1];
                this.jsfId = jsfId.substring(0, jsfId.length() - windowId.length() - 1);
            } else {
                windowId = "";
                this.jsfId = jsfId;
            }
        }

        @Override
        public void run() {
            window.runJSFAction(form, jsfId, windowId);
        }
    }
    
    JSFRunner jsfRunner;

    public JSFAction(String label, JSWindow window, String jsfId) {
        super(label);
        this.jsfRunner = new JSFRunner(window, jsfId);
    }

    public JSFAction(String label, Icon icon, JSWindow window, String jsfId) {
        super(label, icon);
        this.jsfRunner = new JSFRunner(window, jsfId);
    }

    /**
     * User has selected an item, run the associated applet dialog.
     *
     * @param e the action event
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        SwingUtilities.invokeLater(jsfRunner);
    }
}
